import pandas as pd
import os
import json
import uuid
import requests
from pathlib import Path
from typing import Dict, List, Any
from .lip_sync_generator import LipSyncGenerator
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class BatchLipsyncProcessor:
    """
    批量对口型视频处理器
    根据Excel文件中的对话信息批量生成对口型视频
    """
    
    def __init__(self):
        self.generator = LipSyncGenerator()
    
    def process_excel_file(self, excel_path: str, output_dir: str = None) -> Dict[str, Any]:
        """
        处理Excel文件，批量生成对口型视频
        
        Args:
            excel_path (str): Excel文件路径
            output_dir (str): 输出目录路径
            
        Returns:
            dict: 处理结果
        """
        try:
            # 读取Excel文件
            df = pd.read_excel(excel_path)
            
            # 验证必要的列是否存在
            required_columns = ['视频编号', '讲话人类型', '文本内容']
            missing_columns = [col for col in required_columns if col not in df.columns]
            if missing_columns:
                return {
                    'success': False,
                    'error': f'Excel文件缺少必要列: {missing_columns}'
                }
            
            # 按视频编号分组
            grouped_dialogues = df.groupby('视频编号')
            
            # 创建输出目录
            if not output_dir:
                output_dir = os.path.join(os.path.dirname(excel_path), 'lipsync_output')
            
            output_path = Path(output_dir)
            output_path.mkdir(parents=True, exist_ok=True)
            
            # 处理结果统计
            total_videos = len(grouped_dialogues)
            completed_videos = 0
            results = []
            
            logger.info(f"开始处理 {total_videos} 个视频")
            
            # 处理每个视频组
            for video_id, group in grouped_dialogues:
                try:
                    logger.info(f"处理视频编号: {video_id}")
                    
                    # 构建对话数据
                    dialogue_data = self._build_dialogue_data(group)
                    
                    # 生成视频
                    video_result = self.generator.generate_lipsync_video_from_json(dialogue_data)
                    
                    if video_result["success"]:
                        # 下载视频到指定目录
                        video_local_path = None
                        if "video_url" in video_result and video_result["video_url"]:
                            video_filename = f"{video_id}.mp4"
                            video_local_path = os.path.join(output_dir, video_filename)
                            try:
                                # 下载视频文件
                                response = requests.get(video_result["video_url"])
                                if response.status_code == 200:
                                    with open(video_local_path, 'wb') as f:
                                        f.write(response.content)
                                    logger.info(f"视频 {video_id} 已下载到: {video_local_path}")
                                else:
                                    logger.error(f"下载视频 {video_id} 失败，状态码: {response.status_code}")
                                    video_local_path = None
                            except Exception as e:
                                logger.error(f"下载视频 {video_id} 时出错: {str(e)}")
                                video_local_path = None
                        
                        completed_videos += 1
                        results.append({
                            'video_id': video_id,
                            'status': 'completed',
                            'video_url': video_result["video_url"],
                            'video_local_path': video_local_path,
                            'folder_path': video_result["folder_path"]
                        })
                        logger.info(f"视频 {video_id} 生成成功")
                    else:
                        results.append({
                            'video_id': video_id,
                            'status': 'failed',
                            'error': video_result.get("error", "未知错误")
                        })
                        logger.error(f"视频 {video_id} 生成失败: {video_result.get('error', '未知错误')}")
                        
                except Exception as e:
                    completed_videos += 1
                    results.append({
                        'video_id': video_id,
                        'status': 'failed',
                        'error': str(e)
                    })
                    logger.error(f"处理视频 {video_id} 时出错: {str(e)}")
            
            success_count = sum(1 for r in results if r['status'] == 'completed')
            
            return {
                'success': True,
                'total_videos': total_videos,
                'completed_videos': success_count,
                'results': results
            }
            
        except Exception as e:
            logger.error(f"处理Excel文件时出错: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def _build_dialogue_data(self, group_df: pd.DataFrame) -> Dict[str, Any]:
        """
        根据分组数据构建对话数据
        
        Args:
            group_df (pd.DataFrame): 分组的DataFrame
            
        Returns:
            dict: 对话数据
        """
        dialogue = []
        
        for _, row in group_df.iterrows():
            speaker_type = row['讲话人类型']
            text_content = row['文本内容']
            
            # 标准化讲话人类型
            if speaker_type in ['左', 'left']:
                speaker = 'left'
            elif speaker_type in ['右', 'right']:
                speaker = 'right'
            elif speaker_type in ['唯一', 'unique']:
                speaker = 'unique'
            else:
                speaker = speaker_type  # 保持原始值
            
            dialogue_entry = {
                'speaker': speaker,
                'text': text_content
            }
            
            dialogue.append(dialogue_entry)
        
        # 检查是否是单人说话场景
        speakers = set(entry['speaker'] for entry in dialogue)
        if len(speakers) == 1 and 'unique' in speakers:
            # 单人说话场景
            return {
                'background_image': None,
                'dialogue': dialogue
            }
        else:
            # 多人对话场景
            return {
                'background_image': None,
                'dialogue': dialogue
            }


def process_batch_lipsync(excel_path: str, output_dir: str = None, task_id: str = None) -> Dict[str, Any]:
    """
    处理批量对口型视频生成任务
    
    Args:
        excel_path (str): Excel文件路径
        output_dir (str): 输出目录
        task_id (str): 任务ID
        
    Returns:
        dict: 处理结果
    """
    processor = BatchLipsyncProcessor()
    return processor.process_excel_file(excel_path, output_dir)